﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.ComponentModel;
using SharpShare.Configuration;

namespace SharpShare.Afp.Configuration {
    public class UserElement : ConfigurationElement, IKeyedElement {
        [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
        public string Name {
            get {
                return (string)this["name"];
            }
            set {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("canChangePassword", DefaultValue = true, IsRequired = false)]
        public bool CanChangePassword {
            get {
                return (bool)this["canChangePassword"];
            }
            set {
                this["canChangePassword"] = value;
            }
        }

        [ConfigurationProperty("password")]
        public string Password {
            get {
                return (string)this["password"];
            }
            set {
                this["password"] = value;
            }
        }

        [ConfigurationProperty("identifier")]
        [TypeConverter(typeof(GuidConverter))]
        public Guid Identifier {
            get {
                Guid id = (Guid)this["identifier"];
                if (id == Guid.Empty) {
                    using (System.Security.Cryptography.SHA256CryptoServiceProvider sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider()) {
                        id = new Guid(sha256.ComputeHash(System.Text.Encoding.ASCII.GetBytes("_user_" + this.Name)).Take(16).ToArray());
                        this["identifier"] = id;
                    }
                }

                return id;
            }
            set {
                this["identifier"] = value;
            }
        }

        [ConfigurationProperty("groups")]
        [TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
        public CommaDelimitedStringCollection Groups {
            get {
                return (CommaDelimitedStringCollection)this["groups"];
            }
            set {
                this["groups"] = value;
            }
        }

        [ConfigurationProperty("metadata")]
        public NameValueConfigurationCollection Metadata {
            get {
                return (NameValueConfigurationCollection)this["metadata"];
            }
            set {
                this["metadata"] = value;
            }
        }

        #region IKeyedElement Members

        string IKeyedElement.Key {
            get { return this.Name; }
        }

        #endregion
    }
}
